<script setup>
import { ref, onMounted } from 'vue';
import { getUserInfor,updateUserInfor,sendVerificationEmail,updateUserPass } from '@/api/user.js';
import { ElDialog, ElMessage } from 'element-plus';

const userInfor = ref([]);
const userId = ref('');
const history = ref([]);
const editDialogVisible = ref(false);  // 控制编辑框的显示与隐藏
const editUserInfor = ref({}); // 用于编辑的用户信息
const passwordDialogVisible = ref(false);
const infor = ref({
    username:'',
    email:'',
    code:'',
    password:''
})

//重置数据
const information = () => {
  infor.value = {
    username: '',
    email: '',
    code: '',
    password: ''
  };
};

// 获取用户信息
const list = async () => {
  try {
    const resp = await getUserInfor(userId.value); // 使用获取到的 userId
    userInfor.value = resp.data.userInfor; // 这里是响应式对象
    history.value = resp.data.history;
    // ElMessage.success("获取数据成功")
  } catch (error) {
    ElMessage.error("获取用户信息失败");
  }
};

// 打开编辑框并传递数据
const openEditDialog = () => {
  editUserInfor.value = { ...userInfor.value };  // 深拷贝用户信息到编辑对象
  editDialogVisible.value = true;  // 打开编辑框
};

// 更新用户信息
const updateUserInfo = async () => {
  // 在此处添加调用API更新用户信息的逻辑
  try {
    await updateUserInfor(editUserInfor.value)
    // console.log('用户信息更新:', editUserInfor.value);
    ElMessage.success('信息更新成功');
    editDialogVisible.value = false;  // 关闭编辑框
    list()
  } catch (error) {
    ElMessage.error("修改失败，请重试。")
  }
  
};

//修改密码
const isCounting = ref(false);
const countdown = ref(60);
// 打开更改密码对话框
const openPasswordDialog = () => {
  passwordDialogVisible.value = true;
  infor.value = { 
    ...userInfor.value,
    password: '',  // 将 password 赋值为空
    email:''
  };
};

//关闭
const closeEdit = () => {
    passwordDialogVisible.value = false;
    information()
}


//将email传给后端来发送验证码
const sendVerificationCode = async () => {
  if (isCounting.value) return;

  // 确保用户输入的邮箱不为空
  if (!infor.value.email) {
    ElMessage.error('请输入邮箱地址');
    return;
  }

  try {
    // 调用后端接口发送验证码
    await sendVerificationEmail(infor.value.email);
    ElMessage.success('验证码已发送，请查看您的邮箱');

    // 开始倒计时
    isCounting.value = true;
    countdown.value = 60;

    const interval = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(interval);
        isCounting.value = false;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error('发送验证码失败，请重试。');
    console.error(error); // 打印错误以便调试
  }
};

//提交修改密码
const updateUserPassword = async () => {
  try {
    if (!infor.value.email || !infor.value.code || !infor.value.password) {
      ElMessage.error('请填写所有必填项');
      return;
    }

    const response = await updateUserPass(infor.value);
    console.log(infor.value)
    if (response.data === "密码更新成功") { 
      ElMessage.success('密码修改成功');
      passwordDialogVisible.value = false;
      information();
    } else {
      ElMessage.error('修改密码失败: ' + response.message);
    }
  } catch (error) {
    ElMessage.error('修改密码失败，请重试。');
    console.error(error);
  }
};


onMounted(() => {
  // 获取 URL 查询参数
  const params = new URLSearchParams(window.location.search);
  userId.value = params.get('userId'); // 获取 userId
  // console.log(userId.value)

  // 确保 userId 不为空
  if (userId.value) {
    list(); // 调用获取用户信息的函数
  }
});
</script>

<template>
  <el-card class="page-container">
    <div style="height: 50px;background-color: #9ac7f7;line-height: 50px;color:white;">
      <span style="margin-left: 100px">个人信息</span>
    </div>

    <el-row style="margin-top: 20px">
      <el-col :span="12" style="margin: 0 auto;">
        <el-form :model="userInfor" label-width="100px" size="large">
          <!-- 个人信息展示区域 -->
          <el-row justify="center">
            <el-col :span="10">
              <el-form-item label="姓名" prop="username">
                <el-input v-model="userInfor.username" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="学号" prop="studentId">
                <el-input v-model="userInfor.studentId" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row justify="center">
            <el-col :span="10">
              <el-form-item label="学院" prop="collegeId">
                <el-input v-model="userInfor.collegename" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="班级" prop="classId">
                <el-input v-model="userInfor.classname" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row justify="center">
            <el-col :span="10">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="userInfor.phone" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfor.email" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row justify="center" style="margin-top: 20px;">
            <el-col :span="10" style="text-align: center;">
              <el-button type="primary" @click="openEditDialog">修改信息</el-button>
              <el-button type="primary" @click="openPasswordDialog" style="margin-left: 10px;">更改密码</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-col>

      <el-col>
        <div style="margin-top: 30px; text-align: center;">
          <span>历史记录</span>
        </div>
        <div style="display: flex; justify-content: center; margin-top: 10px;">
          <el-table :data="history" style="width: 50%; min-height: 550px">
            <el-table-column label="登陆IP地址" width="400" prop="ip"></el-table-column>
            <el-table-column label="上次登陆时间" prop="time"></el-table-column>
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
        </div>
      </el-col>
    </el-row>

    <!-- 编辑用户信息的模态框 -->
    <el-dialog v-model="editDialogVisible" title="修改信息" width="500px">
      <el-form :model="editUserInfor" label-width="100px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="editUserInfor.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="editUserInfor.studentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="collegeId">
          <el-input v-model="editUserInfor.collegename" disabled></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-input v-model="editUserInfor.classname" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editUserInfor.phone" ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserInfor.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUserInfo">保存</el-button>
      </span>
    </el-dialog>

    <!-- 更改密码的模态框 -->
    <el-dialog v-model="passwordDialogVisible" title="更改密码" width="400px">
      <el-form :model="infor" label-width="100px" style="padding: 20px;">
        <el-form-item label="姓名" prop="username" >
          <el-input v-model="infor.username" placeholder="请输入姓名" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="infor.email" placeholder="请输入邮箱" type="email"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div style="display: flex; align-items: center;">
            <el-input v-model="infor.code" placeholder="请输入验证码" style="flex: 1;"></el-input>
            <el-button
              :disabled="isCounting"
              @click="sendVerificationCode"
              type="primary"
              size="small"
              style="margin-left: 10px;"
            >
              {{ isCounting ? countdown + '秒' : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="infor.password" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeEdit" >取消</el-button>
        <el-button type="primary" @click="updateUserPassword">保存</el-button>
      </span>
    </el-dialog>

  </el-card>
</template>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-form-item {
  margin-bottom: 20px; /* 调整每个表单项的底部间距 */
}
</style>
  